<?php
// 数据库配置
$servername = "localhost";
$username = "db_user";
$password = "db_password";
$dbname = "db_name";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("数据库连接失败: " . $conn->connect_error);
}

// 创建数据库表（如果不存在）
$sql = "CREATE TABLE IF NOT EXISTS rooms (
    id INT AUTO_INCREMENT PRIMARY KEY,
    room_code VARCHAR(8) UNIQUE NOT NULL,
    is_active BOOLEAN DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if (!$conn->query($sql)) {
    die("创建表失败: " . $conn->error);
}

$sql = "CREATE TABLE IF NOT EXISTS words (
    id INT AUTO_INCREMENT PRIMARY KEY,
    room_id INT NOT NULL,
    word VARCHAR(100) NOT NULL,
    hint VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (room_id) REFERENCES rooms(id)
)";

if (!$conn->query($sql)) {
    die("创建表失败: " . $conn->error);
}

// 生成唯一的房间代码
function generateRoomCode() {
    $characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $code = '';
    for ($i = 0; $i < 6; $i++) {
        $code .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $code;
}

// 处理API请求
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    
    switch ($_GET['action']) {
        case 'create_room':
            $roomCode = generateRoomCode();
            $stmt = $conn->prepare("INSERT INTO rooms (room_code) VALUES (?)");
            $stmt->bind_param("s", $roomCode);
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'room_code' => $roomCode]);
            } else {
                echo json_encode(['success' => false, 'message' => '房间创建失败']);
            }
            exit;
            
        case 'submit_word':
            $roomCode = $_POST['room_code'] ?? '';
            $word = $_POST['word'] ?? '';
            $hint = $_POST['hint'] ?? '';
            
            if (empty($roomCode) || empty($word)) {
                echo json_encode(['success' => false, 'message' => '参数不完整']);
                exit;
            }
            
            // 获取房间ID
            $stmt = $conn->prepare("SELECT id FROM rooms WHERE room_code = ?");
            $stmt->bind_param("s", $roomCode);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 0) {
                echo json_encode(['success' => false, 'message' => '房间不存在']);
                exit;
            }
            
            $room = $result->fetch_assoc();
            $roomId = $room['id'];
            
            // 保存词语
            $stmt = $conn->prepare("INSERT INTO words (room_id, word, hint) VALUES (?, ?, ?)");
            $stmt->bind_param("iss", $roomId, $word, $hint);
            if ($stmt->execute()) {
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => '词语提交失败']);
            }
            exit;
            
        case 'get_latest_word':
            $roomCode = $_GET['room_code'] ?? '';
            
            if (empty($roomCode)) {
                echo json_encode(['success' => false, 'message' => '参数不完整']);
                exit;
            }
            
            // 获取最新词语
            $stmt = $conn->prepare("SELECT w.word, w.hint FROM words w 
                                   JOIN rooms r ON w.room_id = r.id 
                                   WHERE r.room_code = ? 
                                   ORDER BY w.created_at DESC 
                                   LIMIT 1");
            $stmt->bind_param("s", $roomCode);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $wordData = $result->fetch_assoc();
                echo json_encode(['success' => true, 'word' => $wordData['word'], 'hint' => $wordData['hint']]);
            } else {
                echo json_encode(['success' => false, 'message' => '无可用词语']);
            }
            exit;
            
        case 'close_room':
            $roomCode = $_GET['room_code'] ?? '';
            
            if (empty($roomCode)) {
                echo json_encode(['success' => false, 'message' => '参数不完整']);
                exit;
            }
            
            $stmt = $conn->prepare("UPDATE rooms SET is_active = 0 WHERE room_code = ?");
            $stmt->bind_param("s", $roomCode);
            if ($stmt->execute()) {
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => '关闭房间失败']);
            }
            exit;
            
        case 'reopen_room':
            $roomCode = $_GET['room_code'] ?? '';
            
            if (empty($roomCode)) {
                echo json_encode(['success' => false, 'message' => '参数不完整']);
                exit;
            }
            
            $stmt = $conn->prepare("UPDATE rooms SET is_active = 1 WHERE room_code = ?");
            $stmt->bind_param("s", $roomCode);
            if ($stmt->execute()) {
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => '开启房间失败']);
            }
            exit;
            
        case 'check_room_status':
            $roomCode = $_GET['room_code'] ?? '';
            
            if (empty($roomCode)) {
                echo json_encode(['success' => false, 'message' => '参数不完整']);
                exit;
            }
            
            $stmt = $conn->prepare("SELECT is_active FROM rooms WHERE room_code = ?");
            $stmt->bind_param("s", $roomCode);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 0) {
                echo json_encode(['success' => false, 'message' => '房间不存在']);
            } else {
                $room = $result->fetch_assoc();
                echo json_encode(['success' => true, 'is_active' => (bool)$room['is_active']]);
            }
            exit;
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>头顶猜词游戏</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="preconnect" href="https://fontsapi.zeoseven.com" crossorigin />
    <link rel="stylesheet"
    href="https://fontsapi.zeoseven.com/84/main/result.css"
    onerror="this.href='https://fontsapi-storage.zeoseven.com/84/main/result.css'" />
    <style>
        :root {
            --primary: #6c5ce7;
            --secondary: #a29bfe;
            --success: #00b894;
            --warning: #fdcb6e;
            --danger: #ff7675;
            --dark: #2d3436;
            --light: #f7f9fc;
            --card-bg: rgba(255, 255, 255, 0.85);
            --shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            --giver-gradient: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
            --guesser-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --home-gradient: linear-gradient(135deg, #a29bfe 0%, #6c5ce7 100%);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'DouyinSans', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: var(--home-gradient);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
            color: var(--dark);
            transition: background 0.5s ease;
            overflow-x: hidden;
        }

        body.giver-mode {
            background: var(--giver-gradient);
        }

        body.guesser-mode {
            background: var(--guesser-gradient);
        }

        .container {
            max-width: 1200px;
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 30px;
        }

        header {
            text-align: center;
            margin-bottom: 20px;
            animation: fadeInDown 0.8s ease;
        }

        h1 {
            color: white;
            font-size: 3.2rem;
            text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            margin-bottom: 10px;
        }

        .subtitle {
            color: rgba(255, 255, 255, 0.85);
            font-size: 1.4rem;
            max-width: 700px;
            margin: 0 auto 20px;
        }

        /* 首页样式 */
        #homeScreen {
            width: 100%;
            animation: fadeIn 0.8s ease;
        }

        .home-panel {
            background: var(--card-bg);
            border-radius: 24px;
            padding: 50px;
            box-shadow: var(--shadow);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.3);
            text-align: center;
            animation: fadeInUp 0.8s ease;
            transition: all 0.3s ease;
        }

        .home-panel:hover {
            transform: translateY(-10px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
        }

        .role-selection {
            display: flex;
            justify-content: center;
            gap: 40px;
            margin-top: 40px;
            flex-wrap: wrap;
        }

        .role-card {
            background: white;
            border-radius: 20px;
            padding: 40px 30px;
            width: 320px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .role-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
        }

        .role-card.giver {
            background: var(--giver-gradient);
        }

        .role-card.guesser {
            background: var(--guesser-gradient);
        }

        .role-icon {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 25px;
            font-size: 3rem;
            color: var(--primary);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .role-card.giver .role-icon {
            background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
            color: white;
        }

        .role-card.guesser .role-icon {
            background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
            color: white;
        }

        .role-title {
            font-size: 2rem;
            margin-bottom: 15px;
            color: white;
            text-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        .role-description {
            font-size: 1.1rem;
            color: rgba(255, 255, 255, 0.95);
            line-height: 1.6;
            margin-bottom: 25px;
        }

        .btn {
            display: inline-block;
            background: white;
            color: var(--primary);
            padding: 15px 35px;
            border-radius: 50px;
            font-size: 1.2rem;
            font-weight: 700;
            text-decoration: none;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
            transition: all 0.3s ease;
        }

        .btn:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
        }

        /* 游戏面板通用样式 */
        .game-panel {
            background: var(--card-bg);
            border-radius: 24px;
            padding: 40px;
            box-shadow: var(--shadow);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.3);
            transition: all 0.3s ease;
            display: none;
            animation: fadeIn 0.8s ease;
            position: relative;
            overflow: hidden;
            max-width: 800px;
            margin: 0 auto;
            width: 100%;
        }

        .panel-header {
            display: flex;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid rgba(0, 0, 0, 0.05);
        }

        .panel-title {
            font-size: 2.2rem;
            font-weight: 700;
            color: var(--primary);
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .panel-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.8rem;
        }

        .form-group {
            margin-bottom: 30px;
        }

        label {
            display: block;
            margin-bottom: 12px;
            font-weight: 600;
            color: var(--dark);
            font-size: 1.2rem;
        }

        input, textarea, button {
            width: 100%;
            padding: 18px 25px;
            border-radius: 18px;
            border: none;
            font-size: 1.1rem;
            transition: all 0.3s ease;
        }

        input, textarea {
            background: rgba(255, 255, 255, 0.7);
            border: 2px solid rgba(0, 0, 0, 0.05);
            box-shadow: inset 2px 2px 5px rgba(209, 217, 230, 0.5),
                        inset -2px -2px 5px rgba(255, 255, 255, 0.7);
        }

        input:focus, textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: inset 2px 2px 5px rgba(209, 217, 230, 0.5),
                        inset -2px -2px 5px rgba(255, 255, 255, 0.7),
                        0 0 0 3px rgba(108, 92, 231, 0.2);
        }

        button {
            color: white;
            font-weight: 700;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        button:hover {
            transform: translateY(-3px);
        }

        button:active {
            transform: translateY(1px);
        }

        .btn-primary {
            background: linear-gradient(to right, var(--primary), var(--secondary));
            box-shadow: 0 5px 15px rgba(108, 92, 231, 0.4);
        }

        .btn-primary:hover {
            box-shadow: 0 8px 20px rgba(108, 92, 231, 0.6);
        }

        .btn-success {
            background: linear-gradient(to right, var(--success), #55efc4);
            box-shadow: 0 5px 15px rgba(0, 184, 148, 0.4);
        }

        .btn-success:hover {
            box-shadow: 0 8px 20px rgba(0, 184, 148, 0.6);
        }

        .btn-danger {
            background: linear-gradient(to right, var(--danger), #d63031);
            box-shadow: 0 5px 15px rgba(255, 118, 117, 0.4);
        }

        .btn-danger:hover {
            box-shadow: 0 8px 20px rgba(255, 118, 117, 0.6);
        }

        .btn-secondary {
            background: linear-gradient(to right, #636e72, #2d3436);
            box-shadow: 0 5px 15px rgba(45, 52, 54, 0.4);
        }

        .btn-secondary:hover {
            box-shadow: 0 8px 20px rgba(45, 52, 54, 0.6);
        }

        .code-display {
            display: flex;
            align-items: center;
            gap: 15px;
            margin: 20px 0;
        }

        .code {
            flex: 1;
            background: rgba(255, 255, 255, 0.7);
            border-radius: 18px;
            padding: 20px;
            font-size: 2.2rem;
            font-weight: 700;
            text-align: center;
            letter-spacing: 4px;
            color: var(--primary);
            box-shadow: 8px 8px 16px rgba(209, 217, 230, 0.8),
                        -8px -8px 16px rgba(255, 255, 255, 0.8);
        }

        .word-display {
            background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
            border-radius: 24px;
            padding: 60px 30px;
            text-align: center;
            font-size: 4.5rem;
            font-weight: 900;
            color: white;
            text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            min-height: 280px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 30px 0;
            box-shadow: var(--shadow);
            transition: all 0.3s ease;
        }

        .word-display.waiting {
            background: linear-gradient(135deg, #a29bfe 0%, #6c5ce7 100%);
            font-size: 2rem;
            font-weight: 600;
        }

        .status {
            padding: 18px;
            border-radius: 18px;
            margin: 25px 0;
            text-align: center;
            font-weight: 600;
            font-size: 1.2rem;
        }

        .status.connected {
            background: rgba(0, 184, 148, 0.2);
            color: #00b894;
        }

        .status.disconnected {
            background: rgba(255, 118, 117, 0.2);
            color: #ff7675;
        }

        .copy-btn {
            width: auto;
            padding: 15px 25px;
            border-radius: 18px;
            background: rgba(255, 255, 255, 0.7);
            color: var(--primary);
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .copy-btn:hover {
            background: rgba(255, 255, 255, 0.9);
        }

        .timer {
            font-size: 1.5rem;
            text-align: center;
            margin-top: 20px;
            color: var(--primary);
            font-weight: 700;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .back-btn {
            position: absolute;
            top: 30px;
            left: 30px;
            background: rgba(255, 255, 255, 0.7);
            border-radius: 50%;
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: var(--primary);
            cursor: pointer;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            z-index: 100;
        }

        .back-btn:hover {
            transform: translateX(-5px);
            background: white;
        }

        .hint-display {
            font-size: 2rem;
            margin-top: 30px;
            color: #ffeaa7;
            font-weight: 600;
        }

        .instructions {
            background: rgba(255, 255, 255, 0.6);
            border-radius: 18px;
            padding: 25px;
            margin-top: 30px;
            text-align: left;
        }

        .instructions h3 {
            margin-bottom: 20px;
            color: var(--primary);
            display: flex;
            align-items: center;
            gap: 15px;
            font-size: 1.4rem;
        }

        .instructions ol {
            padding-left: 25px;
        }

        .instructions li {
            margin-bottom: 15px;
            line-height: 1.6;
            font-size: 1.1rem;
        }

        .room-status {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
            font-size: 1.1rem;
            font-weight: 600;
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
        }

        .status-active {
            background-color: #00b894;
        }

        .status-inactive {
            background-color: #ff7675;
        }

        .room-controls {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }

        .room-controls button {
            flex: 1;
        }

        .message-box {
            position: fixed;
            top: 30px;
            left: 50%;
            transform: translateX(-50%);
            padding: 15px 30px;
            border-radius: 50px;
            color: white;
            font-weight: 600;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s, transform 0.3s;
        }

        .message-box.success {
            background: linear-gradient(to right, #00b894, #55efc4);
        }

        .message-box.error {
            background: linear-gradient(to right, #ff7675, #d63031);
        }

        .message-box.show {
            opacity: 1;
            transform: translate(-50%, 0);
        }

        /* 动画 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes fadeInDown {
            from { opacity: 0; transform: translateY(-30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* 响应式设计 */
        @media (max-width: 900px) {
            .role-selection {
                flex-direction: column;
                align-items: center;
            }
            
            .role-card {
                width: 100%;
                max-width: 400px;
            }
            
            .home-panel {
                padding: 30px 20px;
            }
            
            h1 {
                font-size: 2.5rem;
            }
            
            .subtitle {
                font-size: 1.2rem;
            }
        }

        @media (max-width: 600px) {
            .word-display {
                font-size: 3rem;
                padding: 40px 20px;
                min-height: 200px;
            }
            
            .code {
                font-size: 1.8rem;
                padding: 15px;
            }
            
            .panel-header {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }
            
            .panel-title {
                font-size: 1.8rem;
            }
            
            .room-controls {
                flex-direction: column;
            }
        }
        /* 新增：首页版权和备案信息样式 */
.home-footer {
    width: 100%;
    background: rgba(0, 0, 0, 0.7);
    color: rgba(255, 255, 255, 0.8);
    text-align: center;
    padding: 15px 0;
    margin-top: 30px;
    font-size: 0.9rem;
    border-radius: 12px;
    backdrop-filter: blur(5px);
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.home-footer a {
    color: #a29bfe;
    text-decoration: none;
    margin: 0 8px;
    transition: color 0.3s ease;
}

.home-footer a:hover {
    color: #6c5ce7;
    text-decoration: underline;
}

.footer-content {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.beian-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-right: 5px;
}

@media (max-width: 768px) {
    .home-footer {
        padding: 10px 0;
        font-size: 0.8rem;
    }
    
    .footer-content {
        flex-direction: column;
        gap: 5px;
    }
}
</style>
    </style>
</head>
<body>
    <div class="container">
        <!-- 首页 -->
        <div id="homeScreen">
            <header>
                <h1><i class="fas fa-brain"></i> 头顶猜词游戏</h1>
                <p class="subtitle">双人互动猜词游戏 - 一人出词，一人猜词，欢乐无限！</p>
            </header>
            
            <div class="home-panel">
                <h2>请选择您的角色</h2>
                <p>选择您在本轮游戏中的身份，开始游戏吧！</p>
                
                <div class="role-selection">
                    <div class="role-card giver" id="giverRole">
                        <div class="role-icon">
                            <i class="fas fa-edit"></i>
                        </div>
                        <h3 class="role-title">主持人</h3>
                        <p class="role-description">创建游戏房间，输入词语让其他人猜。您将看到连接码并与猜词人分享。</p>
                        <div class="btn">成为主持人</div>
                    </div>
                    
                    <div class="role-card guesser" id="guesserRole">
                        <div class="role-icon">
                            <i class="fas fa-user-check"></i>
                        </div>
                        <h3 class="role-title">猜词人</h3>
                        <p class="role-description">加入游戏房间，猜出其他人头上的词语。您需要从主持人那里获取连接码。</p>
                        <div class="btn">成为猜词人</div>
                    </div>
                </div>
                
                <div class="instructions">
                    <h3><i class="fas fa-info-circle"></i> 游戏说明</h3>
                    <ol>
                        <li>主持人创建房间并分享连接码</li>
                        <li>猜词人输入连接码加入房间</li>
                        <li>主持人输入词语并发送</li>
                        <li>猜词人设备上会显示词语（其他人可见）</li>
                        <li>猜词人有60秒时间猜出词语</li>
                        <li>主持人可以随时开启或关闭房间</li>
                    </ol>
                </div>
            </div>
        </div>
        
        <!-- 主持人面板 -->
        <div class="game-panel" id="giverPanel">
            <div class="back-btn" id="backToHome">
                <i class="fas fa-arrow-left"></i>
            </div>
            
            <div class="panel-header">
                <div class="panel-icon">
                    <i class="fas fa-edit"></i>
                </div>
                <h2 class="panel-title">主持人控制面板</h2>
            </div>
            
            <div class="form-group">
                <label for="connectionCode">您的房间连接码</label>
                <div class="code-display">
                    <div class="code" id="connectionCode">正在生成...</div>
                    <button class="copy-btn" id="copyCodeBtn">
                        <i class="fas fa-copy"></i> 复制
                    </button>
                </div>
                <div class="status connected" id="giverStatus">
                    <i class="fas fa-circle"></i> 房间已开启，等待猜词人连接...
                </div>
                <div class="room-status">
                    <span class="status-indicator status-active"></span>
                    <span>房间状态: 已开启</span>
                </div>
                <p style="text-align: center; margin-top: 15px; font-size: 1.1rem;">
                    请将此连接码告诉猜词人，他们需要输入此代码加入您的房间
                </p>
            </div>
            
            <div class="form-group">
                <label for="wordInput">输入词语</label>
                <input type="text" id="wordInput" placeholder="输入要让对方猜的词语...">
            </div>
            
            <div class="form-group">
                <label for="hintInput">提示信息 (可选)</label>
                <input type="text" id="hintInput" placeholder="可以添加一些提示信息...">
            </div>
            
            <button id="submitWordBtn" class="btn-primary">
                <i class="fas fa-paper-plane"></i> 发送词语
            </button>
            
            <div class="room-controls">
                <button class="btn-success" id="reopenRoomBtn">
                    <i class="fas fa-door-open"></i> 开启房间
                </button>
                <button class="btn-danger" id="closeRoomBtn">
                    <i class="fas fa-door-closed"></i> 关闭房间
                </button>
            </div>
            
            <div class="instructions">
                <h3><i class="fas fa-info-circle"></i> 主持人指南</h3>
                <ol>
                    <li>将上方连接码告诉猜词人</li>
                    <li>在输入框中输入要让对方猜的词语</li>
                    <li>可选的添加提示信息帮助猜词人</li>
                    <li>点击"发送词语"按钮</li>
                    <li>词语会立即显示在猜词人的设备上</li>
                    <li>使用"开启/关闭房间"按钮控制房间状态</li>
                </ol>
            </div>
        </div>
        
        <!-- 猜词人面板 -->
        <div class="game-panel" id="guesserPanel">
            <div class="back-btn" id="backToHome2">
                <i class="fas fa-arrow-left"></i>
            </div>
            
            <div class="panel-header">
                <div class="panel-icon">
                    <i class="fas fa-user-check"></i>
                </div>
                <h2 class="panel-title">猜词人游戏面板</h2>
            </div>
            
            <div class="form-group">
                <label for="joinCode">输入连接码</label>
                <input type="text" id="joinCode" placeholder="输入主持人提供的连接码...">
            </div>
            
            <button id="joinRoomBtn" class="btn-primary">
                <i class="fas fa-sign-in-alt"></i> 加入房间
            </button>
            
            <div class="status disconnected" id="guessStatus">
                <i class="fas fa-circle"></i> 尚未连接到房间
            </div>
            
            <div class="word-display waiting" id="wordDisplay">
                等待连接...
            </div>
            
            <div class="timer">
                <i class="fas fa-clock"></i> 词语显示时间: <span id="timer">60</span>秒
            </div>
            
            <div class="instructions">
                <h3><i class="fas fa-info-circle"></i> 猜词人指南</h3>
                <ol>
                    <li>向主持人获取连接码并输入</li>
                    <li>点击"加入房间"按钮</li>
                    <li>等待主持人发送词语</li>
                    <li>词语会显示在您设备的上方</li>
                    <li>您有60秒时间猜词（其他人可以看到词语）</li>
                    <li>时间结束后等待下一个词语</li>
                </ol>
            </div>
        </div>
<!-- 首页版权和备案信息 -->
    <footer class="home-footer">
        <div class="footer-content">
            <div>
                <span class="beian-icon">
                    <i class="fas fa-shield-alt"></i>
                </span>
                <a href="https://beian.miit.gov.cn" target="_blank">京ICP备12345678号-9</a>
            </div>
            <div>
                <span class="beian-icon">
                    <i class="fas fa-balance-scale"></i>
                </span>
                <a href="https://www.beian.gov.cn" target="_blank">京公网安备 11000000000123号</a>
            </div>
            <div>
                <span class="beian-icon">
                    <i class="fas fa-code"></i>
                </span>
                <a href="https://gitee.com/SenLin_M/headword" target="_blank">Gitee 开源项目</a>
            </div>
            <div>
                <span class="beian-icon">
                    <i class="far fa-copyright"></i>
                </span>
                2025 SenLinM 版权所有
            </div>
        </div>
    </footer>
</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 页面元素
            const homeScreen = document.getElementById('homeScreen');
            const giverPanel = document.getElementById('giverPanel');
            const guesserPanel = document.getElementById('guesserPanel');
            const giverRole = document.getElementById('giverRole');
            const guesserRole = document.getElementById('guesserRole');
            const backToHome = document.getElementById('backToHome');
            const backToHome2 = document.getElementById('backToHome2');
            
            // 消息框
            const messageBox = document.createElement('div');
            messageBox.className = 'message-box';
            document.body.appendChild(messageBox);
            
            // 全局变量
            let roomCode = '';
            let timerInterval = null;
            let timeLeft = 60;
            let roomActive = true;
            
            // 角色选择
            giverRole.addEventListener('click', function() {
                homeScreen.style.display = 'none';
                giverPanel.style.display = 'block';
                document.body.classList.add('giver-mode');
                
                // 创建房间
                createRoom();
            });
            
            guesserRole.addEventListener('click', function() {
                homeScreen.style.display = 'none';
                guesserPanel.style.display = 'block';
                document.body.classList.add('guesser-mode');
            });
            
            // 返回首页
            backToHome.addEventListener('click', goToHome);
            backToHome2.addEventListener('click', goToHome);
            
            function goToHome() {
                giverPanel.style.display = 'none';
                guesserPanel.style.display = 'none';
                homeScreen.style.display = 'block';
                document.body.classList.remove('giver-mode', 'guesser-mode');
                
                // 重置状态
                if (timerInterval) clearInterval(timerInterval);
                document.getElementById('wordDisplay').innerHTML = '等待连接...';
                document.getElementById('wordDisplay').className = 'word-display waiting';
                document.getElementById('guessStatus').innerHTML = '<i class="fas fa-circle"></i> 尚未连接到房间';
                document.getElementById('guessStatus').className = 'status disconnected';
                document.getElementById('joinRoomBtn').innerHTML = '<i class="fas fa-sign-in-alt"></i> 加入房间';
                document.getElementById('timer').textContent = '60';
            }
            
            // 创建房间
            function createRoom() {
                fetch('?action=create_room')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            roomCode = data.room_code;
                            document.getElementById('connectionCode').textContent = roomCode;
                            roomActive = true;
                            updateRoomStatusUI();
                        } else {
                            showMessage('房间创建失败: ' + data.message, 'error');
                        }
                    });
            }
            
            // 复制连接码功能
            document.getElementById('copyCodeBtn').addEventListener('click', function() {
                const code = document.getElementById('connectionCode').textContent;
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(code).then(() => {
                        showMessage('连接码已复制到剪贴板', 'success');
                    });
                } else {
                    // 兼容旧浏览器
                    const textarea = document.createElement('textarea');
                    textarea.value = code;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                    showMessage('连接码已复制到剪贴板', 'success');
                }
            });
            
            // 提交词语功能
            document.getElementById('submitWordBtn').addEventListener('click', function() {
                const word = document.getElementById('wordInput').value.trim();
                const hint = document.getElementById('hintInput').value.trim();
                
                if (!word) {
                    showMessage('请输入要发送的词语', 'error');
                    return;
                }
                
                if (!roomActive) {
                    showMessage('房间已关闭，请先开启房间', 'error');
                    return;
                }
                
                const formData = new FormData();
                formData.append('room_code', roomCode);
                formData.append('word', word);
                formData.append('hint', hint);
                
                fetch('?action=submit_word', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 清空输入框
                        document.getElementById('wordInput').value = '';
                        document.getElementById('hintInput').value = '';
                        
                        showMessage('词语已成功发送到猜词人设备！', 'success');
                    } else {
                        showMessage('提交失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('提交过程中发生错误', 'error');
                });
            });
            
            // 关闭房间功能
            document.getElementById('closeRoomBtn').addEventListener('click', function() {
                if (confirm('确定要关闭房间吗？关闭后猜词人将无法连接到此房间！')) {
                    fetch(`?action=close_room&room_code=${roomCode}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                roomActive = false;
                                updateRoomStatusUI();
                                showMessage('房间已成功关闭！', 'success');
                            } else {
                                showMessage('关闭房间失败: ' + data.message, 'error');
                            }
                        });
                }
            });
            
            // 开启房间功能
            document.getElementById('reopenRoomBtn').addEventListener('click', function() {
                fetch(`?action=reopen_room&room_code=${roomCode}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            roomActive = true;
                            updateRoomStatusUI();
                            showMessage('房间已重新开启！', 'success');
                        } else {
                            showMessage('开启房间失败: ' + data.message, 'error');
                        }
                    });
            });
            
            // 更新房间状态UI
            function updateRoomStatusUI() {
                const statusElement = document.getElementById('giverStatus');
                const statusIndicator = document.querySelector('.room-status .status-indicator');
                const statusText = document.querySelector('.room-status span:last-child');
                
                if (roomActive) {
                    statusElement.innerHTML = '<i class="fas fa-circle"></i> 房间已开启，等待猜词人连接...';
                    statusElement.className = 'status connected';
                    statusIndicator.className = 'status-indicator status-active';
                    statusText.textContent = '房间状态: 已开启';
                } else {
                    statusElement.innerHTML = '<i class="fas fa-circle"></i> 房间已关闭';
                    statusElement.className = 'status disconnected';
                    statusIndicator.className = 'status-indicator status-inactive';
                    statusText.textContent = '房间状态: 已关闭';
                }
            }
            
            // 加入房间功能
            document.getElementById('joinRoomBtn').addEventListener('click', function() {
                const joinCode = document.getElementById('joinCode').value.trim();
                
                if (!joinCode) {
                    showMessage('请输入连接码', 'error');
                    return;
                }
                
                // 验证房间是否存在
                fetch(`?action=check_room_status&room_code=${joinCode}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            if (data.is_active) {
                                roomCode = joinCode;
                                document.getElementById('guessStatus').innerHTML = '<i class="fas fa-circle"></i> 已连接到房间';
                                document.getElementById('guessStatus').className = 'status connected';
                                document.getElementById('wordDisplay').textContent = '等待主持人发送词语...';
                                document.getElementById('wordDisplay').className = 'word-display waiting';
                                document.getElementById('joinRoomBtn').innerHTML = '<i class="fas fa-sync-alt"></i> 重新连接';
                                
                                // 开始轮询新词语
                                startPolling();
                            } else {
                                showMessage('房间已关闭，无法连接', 'error');
                            }
                        } else {
                            showMessage('房间连接失败: ' + data.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showMessage('连接过程中发生错误', 'error');
                    });
            });
            
            // 开始轮询新词语
            function startPolling() {
                setInterval(() => {
                    if (!roomCode) return;
                    
                    // 检查房间状态
                    fetch(`?action=check_room_status&room_code=${roomCode}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                if (!data.is_active) {
                                    // 房间已关闭
                                    document.getElementById('guessStatus').innerHTML = '<i class="fas fa-circle"></i> 房间已关闭';
                                    document.getElementById('guessStatus').className = 'status disconnected';
                                    document.getElementById('wordDisplay').innerHTML = '房间已关闭，无法接收新词语';
                                    document.getElementById('wordDisplay').className = 'word-display waiting';
                                    clearInterval(timerInterval);
                                    return;
                                }
                                
                                // 获取最新词语
                                fetch(`?action=get_latest_word&room_code=${roomCode}`)
                                    .then(response => response.json())
                                    .then(data => {
                                        if (data.success && data.word) {
                                            const wordDisplay = document.getElementById('wordDisplay');
                                            
                                            // 如果显示的是等待信息或新词语
                                            if (wordDisplay.classList.contains('waiting') || 
                                                wordDisplay.textContent !== data.word) {
                                                
                                                wordDisplay.innerHTML = data.word;
                                                wordDisplay.className = 'word-display';
                                                
                                                if (data.hint) {
                                                    const hintElement = document.createElement('div');
                                                    hintElement.className = 'hint-display';
                                                    hintElement.textContent = `提示: ${data.hint}`;
                                                    wordDisplay.appendChild(hintElement);
                                                }
                                                
                                                // 重置并启动计时器
                                                resetTimer();
                                            }
                                        }
                                    });
                            }
                        });
                }, 1000); // 每2秒轮询一次
            }
            
            // 重置计时器
            function resetTimer() {
                clearInterval(timerInterval);
                timeLeft = 60;
                document.getElementById('timer').textContent = timeLeft;
                
                timerInterval = setInterval(() => {
                    timeLeft--;
                    document.getElementById('timer').textContent = timeLeft;
                    
                    if (timeLeft <= 0) {
                        clearInterval(timerInterval);
                        document.getElementById('wordDisplay').innerHTML = '时间到！请等待下一个词语';
                        document.getElementById('wordDisplay').className = 'word-display waiting';
                    }
                }, 1000);
            }
            
            // 显示消息
            function showMessage(message, type) {
                messageBox.textContent = message;
                messageBox.className = `message-box ${type} show`;
                
                setTimeout(() => {
                    messageBox.classList.remove('show');
                }, 3000);
            }
        });
    </script>
</body>
</html>